package ThreadDemo;

/*
 * Author: JacksonCoder
 * FileName: PingPongBarrier
 * Version: 1.0.0
 * Date: 2025/5/14
 */

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;

public class PingPongBarrier {

    private final AtomicInteger counter = new AtomicInteger(0);
    private final CyclicBarrier barrier;

    public PingPongBarrier(int rounds){
        barrier = new CyclicBarrier(2, () -> {
            int i = counter.getAndIncrement();
            System.out.println(i % 2 == 0 ? "ping" : "pong");
        });
        // rounds × 2 个 barrier.await()，轮流打印
    }

    public void loop(int rounds) throws InterruptedException, BrokenBarrierException{
        for(int i = 0; i < rounds; i++){
            barrier.await();
            barrier.await();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        PingPongBarrier pp = new PingPongBarrier(10);
        Thread t1 = new Thread(() -> {
            try{
                pp.loop(10);
            }catch (Exception e){
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try{
                pp.loop(10);
            }catch (Exception e){
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

    }

}
